import { Inject, Injectable } from '@nestjs/common';
import { CreateUserDto, SelectUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { Prisma } from '@prisma/client';

@Injectable()
export class UserService {

    @Inject()
    private readonly prismaService: PrismaService;

    //分页模糊查询用户
    async findAll(select: SelectUserDto) {
        const { username, email, phone, nickName, page = 1, pageSize = 10 } = select;
        const where: Prisma.UserWhereInput = {
            // 使用 AND 连接多个条件
            AND: [
                username ? { username: { contains: username } } : undefined,
                email ? { email: { contains: email } } : undefined,
                phone ? { phone: { contains: phone } } : undefined,
                nickName ? { nickName: { contains: nickName } } : undefined,
            ].filter(Boolean), // 过滤掉 undefined 条件
        };
        const users = await this.prismaService.user.findMany({
            where,
            skip: (page - 1) * pageSize,
            take: pageSize,
            include: {
                UserRole: {
                    select: {
                        role: {
                            select: {
                                name: true
                            }
                        }
                    }
                },
            }
        });
        const total = await this.prismaService.user.count({
            where,
        });
        return {
            users,
            total,
        };
    }

    // 查询单个用户
    async findOne(id: string) {
        const user = await this.prismaService.user.findUnique({
            where: {
                id
            },
        });
        delete user.password;
        return user;
    }

    // 修改用户
    async update(id: string, updateUserDto: UpdateUserDto) {
        const { avatar } = updateUserDto;
        const user = await this.prismaService.user.update({
            where: {
                id
            },
            data: {
                avatar
            },
        });
        delete user.password;
        return user;
    }

    // 删除用户
    async remove(id: string) {
        const user = await this.prismaService.user.delete({
            where: {
                id
            },
        });
        if (!user) {
            return {
                message: "删除失败"
            }
        } else {
            return {
                message: "删除成功"
            }
        }
    }
}
